#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Common.hpp"
#include "InetAddr.hpp"



using namespace wxd;
void Usage(char* argv[])
{
    std::cerr<<"usage: ./"<<argv[0]<<" port"<<std::endl;
}
int main(int argc,char* argv[])
{
    //  ./TcpClient ip port
    if(argc != 3)
    {
        Usage(argv);
        exit(USAGE_ERR);
    }
    uint16_t server_port = std::stoi(argv[2]);
    std::string server_ip = argv[1];
    //新建套接字
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        std::cerr<<"create socket fail"<<std::endl;
        exit(SOCKET_ERR);
    }
    //成功

    //发起连接请求
    InetAddrTrans peer_trans(server_ip,server_port);
    int n = connect(sockfd,peer_trans.SockaddrPtr(),peer_trans.SockLen());
    if(n < 0)
    {
        std::cerr<<"connect fail"<<std::endl;
        exit(CONNECT_ERR);
    }
    //连接成功
    while(true)
    {
        //从标准输入读取数据
        std::cout<<"please enter# ";
        std::string input;
        std::getline(std::cin,input);
        //发送消息
        int wsize = write(sockfd,input.c_str(),input.size());
        if(wsize < 0)
        {
            std::cerr<<"write error"<<std::endl;
            exit(WRITE_ERR);
        }
        //接收消息
        char read_buff[1024];
        int rsize = read(sockfd,read_buff,sizeof(read_buff)-1);
        if(rsize > 0)
        {
            //读取成功
            read_buff[rsize] = 0;
            //显示到标准输出
            std::cout<<read_buff<<std::endl;
        }
        else if(rsize == 0)
        {
            //写端关闭-服务端关闭
            std::cerr<<"服务端关闭连接"<<std::endl;
            exit(READ_ERR);
        }
        else
        {
            std::cerr<<"读取异常"<<std::endl;
            exit(READ_ERR);
        }

    }
    return 0;
}